package com.SFA.Login;

import java.io.IOException;
import java.util.Hashtable;

import com.FrameWork.Common.AbstractBaseActivity;
import com.FrameWork.Common.MyApplication;
import com.FrameWork.Entity.GlobalInfo;
import com.FrameWork.Synchoronization.SyncModel;
import com.FrameWork.Synchoronization.SynchConfig;
import com.FrameWork.Utils.MessageUtils;
import com.FrameWork.Utils.Utils;
import com.SFA.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

public class LoginManager 
{
	// private static final String TAG = "LoginManager";
	private AbstractBaseActivity owner;
	public String ErrorMessage = null;
	public LoginManager(AbstractBaseActivity owner)
	{
		this.owner = owner;
	}

	public  int login(String userName, String userPwd)
	{
		if (!Utils.checkNetworkIsAvailable(owner))
		{
			MessageUtils.showOkMessageBox(owner,
					owner.getString(R.string.title_Warming),
					owner.getString(R.string.info_NoNetAvailable));
			return -1;
		}

		Hashtable<String, String> loginUser = getLoginUser(userName, userPwd);
		String url = owner.getString(R.string.WebServiceURL) + "SERVICE.ASMX";
		int timeoutBySecond = 30;

		int successful = -1;
		try {
			successful = Login(loginUser, url, timeoutBySecond, owner);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(successful ==100)
		{
			GlobalInfo info = GlobalInfo.GetInstance(owner);
			info.setValue(owner, GlobalInfo.USERPASSWORD, userPwd);
		}
		return successful;
	}


	private boolean checkIfConnectFail(HttpResponse response)
	{
		if (response == null || response.getStatusLine().getStatusCode() != 200)
			return true;
		else
			return false;
	}

	private boolean checkIfLoginFail(JSONObject json) throws JSONException
	{

		return json.getBoolean("LoginSuccessful");

	}



	private String getLoginFailMessage(JSONObject json) throws JSONException
	{
		return json.getString("Message");
	}

	private HttpPost getPostRequest(StringEntity soapData, String Url)
	{
		HttpPost request = new HttpPost(Url);
		request.addHeader("SOAPAction",
				owner.getString(R.string.WebService_Login_SOAPAction));
		request.addHeader("Host", Uri.parse(Url).getHost());
		request.addHeader("Content-Type", "text/xml; charset=utf-8");
		request.setEntity(soapData);
		return request;
	}

	private HttpResponse getResponse(HttpPost request, int TimeoutBySecond)
	{
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams()
		.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
				TimeoutBySecond * 1000);

		HttpResponse response = null;
		try
		{
			response = httpclient.execute(request);
		}
		catch (Exception e)
		{
			e.printStackTrace();


		}

		return response;
	}

	private JSONObject getResponseXML(HttpResponse response) throws IOException
	{
		JSONObject json= null;
		HttpEntity entity = response.getEntity();
		try
		{
			// 使用网页的响应流，获取返回的信息。
			String xml = null;
			if(entity.isStreaming())
				xml = Utils.readContents(entity.getContent());
			else
				xml = EntityUtils.toString(entity,"UTF-8");
			int Start = xml.indexOf("<LoginResult>")+ "<LoginResult>".length();
			int end = xml.indexOf("</LoginResult>");
			xml = (String) xml.subSequence(Start,end);

			json = new JSONObject(xml);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();

		}
		finally
		{
			if(entity != null)
			{
				entity.consumeContent();
			}
			return json;
		}
	}

	private StringEntity getSoapData(Hashtable<String, String> loginUser)
	{
		StringEntity entity = null;
		try
		{
			// 拼接成调用WebService的请求数据。
			entity = new StringEntity(String.format("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
					+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
					+ "<soap:Body>"
					+ "<Login xmlns=\"http://tempuri.org/\">"
					+ "<user>"
					+ "<UserName>%1$s</UserName>"
					+ "<UserPwd>%3$s</UserPwd>"
					+ "<IMEICode>%4$s</IMEICode>"
					+ "<IMSICode>%5$s</IMSICode>"
					+ "<PlatformCode>%6$s</PlatformCode>"
					+ "<VersionCode>%7$s</VersionCode>"
					+ "</user>"
					+ "</Login>"
					+ "</soap:Body>"
					+ "</soap:Envelope>",
					loginUser.get("UserName"),
					"0",
					loginUser.get("UserPwd"),
					loginUser.get("IMEICode"),
					loginUser.get("IMSICode"),
					loginUser.get("PlatformCode"),
					loginUser.get("VersionCode")));
		}
		catch (Exception e1)
		{
			e1.printStackTrace();
			return null;
		}
		return entity;
	}



	private void storeLoginData(JSONObject json,Context context)
	{
		try {
			GlobalInfo info = GlobalInfo.GetInstance(context);
			info.setValue(context, GlobalInfo.USERCODE,json.isNull("UserCode") ? null: json.getString("UserCode"));
			info.setValue(context, GlobalInfo.USERID, json.isNull("UserID") ? null:json.getString("UserID"));
			info.setValue(context, GlobalInfo.PERSONID, json.isNull("PERSON_ID") ? null:json.getString("PERSON_ID"));
			info.setValue(context, GlobalInfo.CABFILE, json.isNull("CabFile") ? null:json.getString("CabFile"));
			info.setValue(context, GlobalInfo.DOMAINID, json.isNull("DomainID") ? 0:json.getInt("DomainID"));
			info.setValue(context,GlobalInfo.EMPLOYEECODE, json.isNull("EmployeeCode") ? null:json.getString("EmployeeCode"));
			info.setValue(context,GlobalInfo.EMPLOYEEID, json.isNull("EmployeeID") ? -1:json.getInt("EmployeeID"));
			info.setValue(context, GlobalInfo.SERVERTIME, json.isNull("ServerTime") ? null:json.getString("ServerTime"));
			info.setValue(context, GlobalInfo.NAME, json.isNull("UserName") ? null:json.getString("UserName"));
			
			String userken = info.getUserToken();
			String newken = json.isNull("UserToken") ? null:json.getString("UserToken");
			boolean initmodel = false;
			if(newken == null || !newken.equals(userken))
				initmodel = true;
			info.setValue(context, GlobalInfo.USERTOKEN, newken);
			SynchConfig config = SynchConfig
					.Instance(context);
			config.setSyncModel(initmodel ? SyncModel.InitialSync : SyncModel.UploadDownload);
			try {
				config.Save();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			GlobalInfo.SaveFunctionList( json.getJSONArray("ValuesList").toString());
		} catch (JSONException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		

	}

	protected   int Login(Hashtable<String, String> loginUser,
			String url,
			int timeoutBySecond2,
			Activity context) throws IOException
			{
		//获取设备的IMEI吗
		StringEntity soapData = getSoapData(loginUser);
		HttpPost request = getPostRequest(soapData, url);
		HttpResponse result = getResponse(request, timeoutBySecond2);
		if (checkIfConnectFail(result))
		{
			return -2;
		}

		JSONObject json = getResponseXML(result);

		try {
			if (!checkIfLoginFail(json))
			{
				this.ErrorMessage = json.getString("Message");
				// 验证登录失败。
				return -3;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -4;
		}
		storeLoginData(json,context);
		return 100;
	}





	private Hashtable<String, String> getLoginUser(String userName,
			String userPwd)
			{
		Hashtable<String, String> loginUser = new Hashtable<String, String>(6);

		loginUser.put("UserName", userName);
		loginUser.put("UserPwd", Utils.GetStringForMD5(userPwd));
		loginUser.put("IMEICode", "");
		loginUser.put("IMSICode", "");
		loginUser.put("PlatformCode", "ANDROID");// TODO:测试使用，实际应设置为Android
		loginUser.put("VersionCode", "1.0.0.0");

		// 获取手机号码
		TelephonyManager tm = (TelephonyManager) owner
				.getSystemService(Context.TELEPHONY_SERVICE);
		String IMEICode = tm.getDeviceId();
		if(TextUtils.isEmpty(IMEICode))
		{
			try
			{
				WifiManager wifi = (WifiManager) owner.getSystemService(Context.WIFI_SERVICE);
				WifiInfo info = wifi.getConnectionInfo();
				IMEICode= info.getMacAddress();
			}
			catch(Exception err)
			{
				err.printStackTrace();
			}
		}
		if (IMEICode != null)
			loginUser.put("IMEICode", IMEICode);

		try
		{
			loginUser.put("VersionCode", owner.getPackageManager()
					.getPackageInfo(owner.getPackageName(), 0).versionName);
		}
		catch (NameNotFoundException e1)
		{
			e1.printStackTrace();
		}

		// TODO:测试使用，加大版本号，就不会自动更新了 。不测试的时候，可以删除（注释）掉
		//loginUser.put("VersionCode", "2.0.0.0");
		return loginUser;
			}


}